﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;
using Owin;

namespace AzureAdDemo
{
    public partial class Startup
    {
        private static string realm = ConfigurationManager.AppSettings["ida:Wtrealm"];
        private static string adfsMetadata = ConfigurationManager.AppSettings["ida:ADFSMetadata"];
        private static string reply = ConfigurationManager.AppSettings["ida:Wreply"];

        public void ConfigureAuth(IAppBuilder app)
        {
            if (string.IsNullOrWhiteSpace(reply))
            {
                ConfigureAuthDefault(app);
            }
            else
            {
                ConfigureAuthReply(app);
            }
        }

        public void ConfigureAuthDefault(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = realm,
                    MetadataAddress = adfsMetadata
                });
        }

        public void ConfigureAuthReply(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                ExpireTimeSpan = TimeSpan.FromHours(4),//指定滑动过期时间
                SlidingExpiration = true,//指定滑动过期时间
                CookieName = ".Auth.AzureAdDemo"//为避免不同子站点相互覆盖Cookie，各应用需单独指定,
            });

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = realm,
                    Wreply = reply,
                    MetadataAddress = adfsMetadata,
                    UseTokenLifetime = false,//不设置ADFS生成的Token过期时间，由上面Cookie中指定ExpireTimeSpan
                });
        }
    }
}